import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

/**
 * Created with IntelliJ IDEA.
 * Description: https://leetcode.cn/problems/permutations-ii/
 * User: LianBao
 * Date: 2025-02-28
 * Time: 22:40
 */
public class Solution3 {
    List<List<Integer>> ret;
    boolean[] check;
    List<Integer> path;

    public List<List<Integer>> permuteUnique(int[] nums) {
        ret = new ArrayList<>();
        check = new boolean[nums.length];
        path = new ArrayList<>();
        Arrays.sort(nums);//排序
        dfs(nums);
        return ret;
    }

    public void dfs(int[] nums) {
        if (path.size() == nums.length) {
            //结束条件
            ret.add(new ArrayList<>(path));
            return;
        }
        //枚举所有的元素
        for (int i = 0; i < nums.length; i++) {
            if (check[i] == true || (i != 0 && nums[i] == nums[i - 1]) && check[i - 1] == false) {
                continue;
                //剪枝,跳过不合法的分支
            } else {
                path.add(nums[i]);
                check[i] = true;
                dfs(nums);
                //恢复现场
                path.remove(path.size() - 1);
                check[i] = false;
            }
        }
    }
}
